package com.ztsoft.user.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztsoft.user.mapper.user.SysDeptMapper;
import com.ztsoft.user.pojo.entity.user.SysDept;
import com.ztsoft.user.pojo.entity.user.SysUser;
import com.ztsoft.user.pojo.vo.user.DeptTree;
import com.ztsoft.user.pojo.vo.user.SysDeptTree;
import com.ztsoft.user.pojo.vo.user.SysDeptVo;
import com.ztsoft.user.pojo.vo.user.UserTree;
import com.ztsoft.user.service.user.SysDeptService;
import com.ztsoft.user.service.user.SysUserService;
import com.ztsoft.user.utils.DeptTreeUtils;
import com.ztsoft.user.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public Result<Object> queryDeptByPage(SysDept dept, Integer currentPage, Integer pageSize) {
        try {
            Map<String, Object> resultMap = new HashMap<>();

            // 构建查询条件
            QueryWrapper<SysDept> queryWrapper = new QueryWrapper<>(dept);
            queryWrapper.orderByAsc("order_num");

            // 分页查询
            IPage<SysDept> page = this.page(new Page<>(currentPage, pageSize), queryWrapper);

            // 数据实体转VO
            List<SysDeptVo> list = JSON.parseArray(JSON.toJSONString(page.getRecords()), SysDeptVo.class);

            resultMap.put("count", page.getTotal());
            resultMap.put("data", list);
            return Result.success(resultMap);
        } catch (Exception e) {
            log.info("出现异常" + e);
            return Result.fail();
        }
    }

    @Override
    public Result<Object> queryDeptTreeSelect() {
        // 查询数据库所有数据
        List<SysDept> list = this.list();
        // 树状部门存放集合
        List<SysDeptTree> sysDeptTreeList = new ArrayList<>();

        // SysDept转SysDeptTree
        for (SysDept dept : list) {
            SysDeptTree sysDeptTree = new SysDeptTree();
            sysDeptTree.setValue(String.valueOf(dept.getDeptId()));
            sysDeptTree.setLabel(dept.getDeptName());
            sysDeptTree.setParentId(String.valueOf(dept.getParentId()));
            sysDeptTreeList.add(sysDeptTree);
        }

        // 构建树状
        List<SysDeptTree> sysDeptTreeInfo = DeptTreeUtils.buildDeptTreeSelect(sysDeptTreeList);

        return Result.success(sysDeptTreeInfo);
    }

    @Override
    public Result<Object> addDept(SysDeptVo sysDeptVo) {
        SysDept dept = BeanUtil.copyProperties(sysDeptVo, SysDept.class);
        boolean isSuccess = this.save(dept);
        if (isSuccess) {
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result<Object> updateDept(SysDeptVo sysDeptVo) {
        SysDept dept = BeanUtil.copyProperties(sysDeptVo, SysDept.class);
        boolean isSuccess = this.updateById(dept);
        if (isSuccess) {
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result<Object> deleteDept(Long id) {
        if (Boolean.TRUE.equals(batchDeleteDept(id))) {
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result<Object> queryDeptTree() {
        Map<String, Object> resultMap = new HashMap<>();

        // 查询数据库所有数据
        List<SysDept> list = this.list();
        // 树状部门存放集合
        List<DeptTree> sysDeptTreeList = new ArrayList<>();

        // SysDept转SysDeptTree
        for (SysDept dept : list) {
            List<UserTree> userTreeList = new ArrayList<>();

            DeptTree deptTree = new DeptTree();
            deptTree.setValue(String.valueOf(dept.getDeptId()));
            deptTree.setLabel(dept.getDeptName());
            deptTree.setParentId(String.valueOf(dept.getParentId()));

            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("dept_id", dept.getDeptId());
            List<SysUser> sysUserList = sysUserService.list(queryWrapper);

            for (SysUser sysUser : sysUserList) {
                UserTree userTree = new UserTree();
                userTree.setValue(sysUser.getUserId());
                userTree.setLabel(sysUser.getUserName());
                userTreeList.add(userTree);
            }

            deptTree.setChildren(userTreeList);
            sysDeptTreeList.add(deptTree);
        }

        // 构建树状
        List<DeptTree> sysDeptTreeInfo = DeptTreeUtils.buildDeptAndUserTree(sysDeptTreeList);

        resultMap.put("id", 3);
        resultMap.put("data", sysDeptTreeInfo);
        return Result.success(resultMap);
    }

    /**
     * 根据树状结构删除父级与子级
     *
     * @param id 主键id
     * @return 删除是否成功
     */
    public Boolean batchDeleteDept(Long id) {
        QueryWrapper<SysDept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        List<SysDept> list = this.list(queryWrapper);
        if (!list.isEmpty()) {
            for (SysDept dept : list) {
                batchDeleteDept(dept.getDeptId());
            }
        }
        return this.removeById(id);
    }

}